export default function WeeklyReport() {
  return {
    $template: `
      <div>
        <button v-if="!show" class="weekly-report-icon" @click="showPanel">写周报</button>
        <div v-else class="weekly-report" :class="{ show: show }">
          <div class="weekly-report-title">周报</div>
          <textarea class="weekly-report-content" :value="reportText"></textarea>
          <div class="weekly-report-footer">
            <button @click="copy">复制</button>
            <button @click="show = false">关闭</button>
          </div>
        </div>
      </div>
    `,
    bugReportText: '',
    taskReportText: '',
    show: false,
    get reportText() {
      return `一、版本需求的开发 总体进度50%
        ${this.taskReportText}
        二、版本Bug的修复
        ${this.bugReportText}
        三、其它事项
      `.replace(/\n {5,}/g, '\n')
    },
    handleEvent(e) {
      e.stopPropagation()
    },
    showPanel() {
      this.show = true;
      this.loadTable()
    },
    loadTable() {
      fetch(
        'https://jira.kemai.cn/rest/qoti-rich-filters/latest/gadgets/table/load-table',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            maximumRows: 100,
            richFilterId: 375,
            startIndex: 0
          })
        }
      ).then(res => res.json())
        .then(res => {
          this.createReport(res.issueRows)
        })
    },
    createReport(rows) {
      const bugs = rows.filter(row => row.fields.issuetype.includes('alt="缺陷"'))
      const tasks = rows.filter(row => !row.fields.issuetype.includes('alt="缺陷"'))

      this.bugReportText = this.getDesc(bugs)
      this.taskReportText = this.getDesc(tasks)
    },
    extractTextFromHTML(htmlString) {
      // 方法1: 使用DOMParser（推荐）
      if (typeof DOMParser !== 'undefined') {
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlString, 'text/html');
        return doc.body.innerText || doc.body.textContent || '';
      }

      // 方法2: 使用临时DOM元素（备选）
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = htmlString;
      return tempDiv.innerText || tempDiv.textContent || '';
    },
    getDesc(rows) {
      return rows.reduce((str, row, index) => {
        const issuekey = this.extractTextFromHTML(row.fields.issuekey).trimStart().trimEnd()
        let summary = this.extractTextFromHTML(row.fields.summary).trimStart().trimEnd()
        summary = summary.match(/\n\s*(.*)/)?.[1] || summary
        return str + `${index + 1}、【${issuekey}】${summary} \n`
      }, '')
    },
    copy() {
      const text = document.querySelector('.weekly-report-content').value
      try {
        navigator.clipboard.writeText(text);
        this.showToast('文本已复制到剪贴板');
      } catch (err) {
        this.showToast('复制失败:', err);
      }
    }
  }
}